package com.guli.cart.conf;

import com.guli.cart.vo.UserInfoVo;
import com.guli.common.utils.MemberVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author: 朱财艺
 * @date : 2022/02/09
 * @Description:
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    //    //threadLocal 作用是防止多个线程同时访问同一变量引发线程不安全问题，同一个线程共享数据，类似map（key,value），只有key不同，值才会不一样

    public static ThreadLocal<UserInfoVo> threadLocal=new ThreadLocal<>();


    /**
     *
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoVo userInfoTo = new UserInfoVo();

        HttpSession session = request.getSession();

        MemberVo user = (MemberVo) session.getAttribute("user");

        if (user!=null){

            userInfoTo.setUserId(user.getId()+"");
        }

        Cookie[] cookies = request.getCookies();
        if (cookies!=null && cookies.length>0){

            for (Cookie cookie : cookies) {

                String name = cookie.getName();
                if ("userkey".equals(name)){

                    userInfoTo.setUserKey(cookie.getValue());

                    userInfoTo.setFlag(true);
                }
            }
        }

        if (StringUtils.isEmpty(userInfoTo.getUserKey())){

            String s = UUID.randomUUID().toString();
            userInfoTo.setUserKey(s);
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoVo userInfoVo = threadLocal.get();

        if (!userInfoVo.isFlag()){

            Cookie userkey = new Cookie("userkey", userInfoVo.getUserKey());

            userkey.setDomain("gulimall.com");

            userkey.setMaxAge(60*60*24*30);

            response.addCookie(userkey);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
